Page({
  data: {
    // 控制选择器显示
    showBgSelector: false,
    showElementSelector: false,
    
    // 背景选择器类型：image 图片背景，color 纯色背景
    bgSelectorType: 'image',
    
    // 背景类型：image 图片背景，color 纯色背景
    backgroundType: 'image',
    
    // 内置背景图片列表（示例）
    backgrounds: [
      '/images/backgrounds/001.jpg',
      '/images/backgrounds/002.jpg',
      '/images/backgrounds/003.jpg',
      '/images/backgrounds/004.jpg',
      '/images/backgrounds/005.jpg',
      '/images/backgrounds/006.jpg',
      '/images/backgrounds/007.jpg',
      '/images/backgrounds/008.jpg',
      '/images/backgrounds/009.jpg',
      '/images/backgrounds/010.jpg',
      '/images/backgrounds/011.jpg',
      '/images/backgrounds/012.jpg',
      '/images/backgrounds/013.jpg',
      '/images/backgrounds/014.jpg',
      '/images/backgrounds/015.jpg',
      '/images/backgrounds/016.jpg',
      '/images/backgrounds/017.jpg',
      '/images/backgrounds/018.jpg',
      '/images/backgrounds/019.jpg',
      '/images/backgrounds/020.jpg',
      '/images/backgrounds/021.jpg',
      '/images/backgrounds/022.jpg',
      '/images/backgrounds/023.jpg',
      '/images/backgrounds/024.jpg',
      '/images/backgrounds/025.jpg',
      '/images/backgrounds/026.jpg',
      '/images/backgrounds/027.jpg'
    ],
    
    // 内置装饰元素列表（示例）
    elements: [
      '/images/elements/element1.png',
      '/images/elements/element2.png',
      '/images/elements/element3.png',
      '/images/elements/element4.png',
      '/images/elements/element5.png',
      '/images/elements/element6.png',
      '/images/elements/element7.png'
    ],
    
    // 预设颜色
    presetColors: [
      '#FF0000', // 红色
      '#00FF00', // 绿色
      '#0000FF', // 蓝色
      '#FFFF00', // 黄色
      '#00FFFF', // 青色
      '#FF00FF', // 品红
      '#FFFFFF', // 白色
      '#000000', // 黑色
      '#FFA500', // 橙色
      '#800080', // 紫色
      '#FFC0CB', // 粉色
      '#A52A2A'  // 棕色
    ],
    
    // 自定义颜色
    customColor: '#07c160',
    
    // 画布比例选项
    aspectRatios: [
      { label: '1:1', value: 1, selected: false },
      { label: '3:4', value: 4/3, selected: true },
      { label: '4:3', value: 3/4, selected: false },
      { label: '16:9', value: 9/16, selected: false },
      { label: '9:16', value: 16/9, selected: false }
    ],
    
    // 当前选中的背景
    selectedBackground: '',
    selectedBackgroundColor: '#07c160',
    
    // 已添加到画布的元素
    addedElements: [] as any[],
    
    // 当前选中的元素ID
    selectedElementId: null,
    
    // 用于生成唯一ID
    elementIdCounter: 0,
    
    // 背景图片的原始尺寸
    bgImageWidth: 0,
    bgImageHeight: 0,
    
    // 画布显示尺寸
    canvasDisplayWidth: 375, // 默认宽度
    canvasDisplayHeight: 667 // 默认高度（手机屏幕高度）
  },

  onLoad() {
    // 初始化时可以设置默认背景
    // this.setData({
    //   selectedBackground: this.data.backgrounds[0]
    // });
  },
  
  onReady() {
    // 获取容器默认尺寸
    const query = wx.createSelectorQuery();
    query.select('.canvas-container-wrapper').boundingClientRect((rect: any) => {
      if (rect) {
        this.setData({
          canvasDisplayWidth: Math.min(rect.width, 375) || 375
        });
        
        // 根据默认选中的比例设置画布高度
        const selectedRatio = this.data.aspectRatios.find((ratio: any) => ratio.selected);
        if (selectedRatio) {
          const displayHeight = this.data.canvasDisplayWidth * selectedRatio.value;
          this.setData({
            canvasDisplayHeight: displayHeight
          });
        }
      }
    }).exec();
  },

  // 选择背景
  selectBackground() {
    this.setData({
      showBgSelector: true
    });
  },

  // 关闭背景选择器
  closeBgSelector() {
    this.setData({
      showBgSelector: false
    });
  },

  // 切换背景选择器类型
  switchBgSelectorType(e: any) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      bgSelectorType: type
    });
  },

  // 设置背景
  setBackground(e: any) {
    const src = e.currentTarget.dataset.src;
    
    // 使用微信API获取图片信息
    wx.getImageInfo({
      src: src,
      success: (res) => {
        // 计算保持宽高比的显示尺寸
        const displayWidth = this.data.canvasDisplayWidth;
        const displayHeight = displayWidth * res.height / res.width;
        
        this.setData({
          selectedBackground: src,
          backgroundType: 'image',
          showBgSelector: false,
          bgImageWidth: res.width,
          bgImageHeight: res.height,
          canvasDisplayHeight: displayHeight
        });
      },
      fail: (err) => {
        console.error('获取图片信息失败:', err);
        // 如果获取失败，使用默认尺寸
        this.setData({
          selectedBackground: src,
          backgroundType: 'image',
          showBgSelector: false
        });
      }
    });
  },

  // 设置纯色背景
  setSolidColorBackground(e: any) {
    const color = e.currentTarget.dataset.color;
    this.setCanvasSizeForColorBackground(color);
  },

  // 自定义颜色输入
  onCustomColorInput(e: any) {
    this.setData({
      customColor: e.detail.value
    });
  },

  // 设置自定义颜色背景
  setCustomColorBackground() {
    const color = this.data.customColor;
    if (this.isValidColor(color)) {
      this.setCanvasSizeForColorBackground(color);
    } else {
      wx.showToast({
        title: '颜色值格式不正确',
        icon: 'none'
      });
    }
  },

  // 验证颜色值是否有效
  isValidColor(color: string): boolean {
    // 支持 #RGB, #RRGGBB 格式
    return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(color);
  },

  // 为纯色背景设置画布尺寸
  setCanvasSizeForColorBackground(color: string) {
    // 获取当前选中的比例
    const selectedRatio = this.data.aspectRatios.find((ratio: any) => ratio.selected);
    let displayHeight = this.data.canvasDisplayWidth;
    
    if (selectedRatio) {
      displayHeight = this.data.canvasDisplayWidth * selectedRatio.value;
    }
    
    // 对于纯色背景，我们使用固定尺寸 (1080x1440) 以保证导出质量
    const width = 1080;
    const height = selectedRatio ? Math.round(1080 * selectedRatio.value) : 1440;
    
    this.setData({
      selectedBackgroundColor: color,
      backgroundType: 'color',
      showBgSelector: false,
      bgImageWidth: width,
      bgImageHeight: height,
      canvasDisplayHeight: displayHeight
    });
  },

  // 选择画布比例
  selectAspectRatio(e: any) {
    const ratioValue = e.currentTarget.dataset.ratio;
    
    // 更新选中状态
    const updatedRatios = this.data.aspectRatios.map((ratio: any) => {
      return {
        ...ratio,
        selected: ratio.value == ratioValue
      };
    });
    
    this.setData({
      aspectRatios: updatedRatios
    });
    
    // 如果当前是纯色背景，更新画布尺寸
    if (this.data.backgroundType === 'color') {
      const displayHeight = this.data.canvasDisplayWidth * ratioValue;
      const width = 1080;
      const height = Math.round(1080 * ratioValue);
      
      this.setData({
        canvasDisplayHeight: displayHeight,
        bgImageWidth: width,
        bgImageHeight: height
      });
    }
    // 如果当前是图片背景，更新画布尺寸
    else if (this.data.selectedBackground) {
      const displayHeight = this.data.canvasDisplayWidth * ratioValue;
      this.setData({
        canvasDisplayHeight: displayHeight
      });
    }
  },

  // 添加元素
  addElement() {
    this.setData({
      showElementSelector: true
    });
  },

  // 关闭元素选择器
  closeElementSelector() {
    this.setData({
      showElementSelector: false
    });
  },

  // 添加元素到画布
  addElementToCanvas(e: any) {
    const src = e.currentTarget.dataset.src;
    const elementId = ++this.data.elementIdCounter;
    
    // 创建新元素（相对于显示尺寸）
    const newElement = {
      id: elementId,
      src: src,
      x: 50,
      y: 50,
      width: 80,
      height: 80,
      active: false
    };
    
    // 添加到已添加元素列表
    this.setData({
      addedElements: [...this.data.addedElements, newElement],
      showElementSelector: false
    });
  },

  // 选择元素（用于激活元素）
  selectElement(e: any) {
    const id = e.currentTarget.dataset.id;
    
    // 更新元素的激活状态
    const updatedElements = this.data.addedElements.map((element: any) => {
      return {
        ...element,
        active: element.id === id
      };
    });
    
    this.setData({
      addedElements: updatedElements,
      selectedElementId: id
    });
  },

  // 删除元素
  deleteElement(e: any) {
    const id = e.currentTarget.dataset.id;
    
    // 从元素列表中移除指定元素
    const updatedElements = this.data.addedElements.filter((element: any) => element.id != id);
    
    this.setData({
      addedElements: updatedElements,
      selectedElementId: null
    });
    
    // 阻止事件冒泡
    return false;
  },

  // 触摸开始事件
  onTouchStart(e: any) {
    const id = e.currentTarget.dataset.id;
    const touches = e.touches;
    
    // 查找被触摸的元素
    const elementIndex = this.data.addedElements.findIndex((element: any) => element.id === id);
    if (elementIndex === -1) return;
    
    const element = this.data.addedElements[elementIndex];
    
    // 如果是双指操作，记录初始距离
    if (touches.length === 2) {
      const touch1 = touches[0];
      const touch2 = touches[1];
      const initialDistance = Math.sqrt(
        Math.pow(touch2.clientX - touch1.clientX, 2) + 
        Math.pow(touch2.clientY - touch1.clientY, 2)
      );
      
      const updatedElements = this.data.addedElements.map((el: any, index: number) => {
        if (index === elementIndex) {
          return {
            ...el,
            active: true,
            scaleMode: true,
            initialDistance: initialDistance,
            initialWidth: el.width,
            initialHeight: el.height,
            initialX: el.x,
            initialY: el.y
          };
        } else {
          return {
            ...el,
            active: false
          };
        }
      });
      
      this.setData({
        addedElements: updatedElements,
        selectedElementId: id
      });
      return;
    }
    
    // 单指操作
    if (touches.length === 1) {
      const touch = touches[0];
      
      // 记录初始位置和触摸点相对元素的位置偏移
      const offsetX = touch.clientX - element.x;
      const offsetY = touch.clientY - element.y;
      
      // 激活当前元素
      const updatedElements = this.data.addedElements.map((el: any, index: number) => {
        if (index === elementIndex) {
          return {
            ...el,
            active: true,
            scaleMode: false,
            offsetX: offsetX,
            offsetY: offsetY
          };
        } else {
          return {
            ...el,
            active: false
          };
        }
      });
      
      this.setData({
        addedElements: updatedElements,
        selectedElementId: id
      });
    }
  },

  // 触摸移动事件
  onTouchMove(e: any) {
    const id = e.currentTarget.dataset.id;
    const touches = e.touches;
    
    // 查找被触摸的元素
    const elementIndex = this.data.addedElements.findIndex((element: any) => element.id === id);
    if (elementIndex === -1) return;
    
    const element = this.data.addedElements[elementIndex];
    
    // 双指缩放
    if (touches.length === 2 && element.scaleMode) {
      const touch1 = touches[0];
      const touch2 = touches[1];
      const currentDistance = Math.sqrt(
        Math.pow(touch2.clientX - touch1.clientX, 2) + 
        Math.pow(touch2.clientY - touch1.clientY, 2)
      );
      
      // 计算缩放比例
      const scale = currentDistance / element.initialDistance;
      const newWidth = element.initialWidth * scale;
      const newHeight = element.initialHeight * scale;
      
      // 保持元素中心点不变
      const centerX = element.initialX + element.initialWidth / 2;
      const centerY = element.initialY + element.initialHeight / 2;
      const newX = centerX - newWidth / 2;
      const newY = centerY - newHeight / 2;
      
      // 限制元素在画布范围内
      const boundedX = Math.max(0, Math.min(newX, this.data.canvasDisplayWidth - newWidth));
      const boundedY = Math.max(0, Math.min(newY, this.data.canvasDisplayHeight - newHeight));
      
      // 更新元素尺寸和位置
      const updatedElements = this.data.addedElements.map((el: any) => {
        if (el.id === id) {
          return {
            ...el,
            x: boundedX,
            y: boundedY,
            width: newWidth,
            height: newHeight
          };
        }
        return el;
      });
      
      this.setData({
        addedElements: updatedElements
      });
      return;
    }
    
    // 单指拖动
    if (touches.length === 1 && !element.scaleMode) {
      const touch = touches[0];
      
      // 更新元素位置（限制在画布范围内）
      const updatedElements = this.data.addedElements.map((el: any) => {
        if (el.id === id) {
          const newX = touch.clientX - el.offsetX;
          const newY = touch.clientY - el.offsetY;
          
          // 限制元素在画布范围内移动
          const boundedX = Math.max(0, Math.min(newX, this.data.canvasDisplayWidth - el.width));
          const boundedY = Math.max(0, Math.min(newY, this.data.canvasDisplayHeight - el.height));
          
          return {
            ...el,
            x: boundedX,
            y: boundedY
          };
        }
        return el;
      });
      
      this.setData({
        addedElements: updatedElements
      });
    }
  },

  // 触摸结束事件
  onTouchEnd(e: any) {
    const id = e.currentTarget.dataset.id;
    
    // 查找被触摸的元素
    const elementIndex = this.data.addedElements.findIndex((element: any) => element.id === id);
    if (elementIndex === -1) return;
    
    const element = this.data.addedElements[elementIndex];
    
    // 如果是缩放模式，需要更新初始位置和尺寸数据，以便后续的单指拖动操作能正确进行
    if (element.scaleMode) {
      const updatedElements = this.data.addedElements.map((el: any) => {
        if (el.id === id) {
          // 更新初始位置和尺寸为当前值
          const updatedElement = {
            ...el,
            initialX: el.x,
            initialY: el.y,
            initialWidth: el.width,
            initialHeight: el.height
          };
          
          // 重新计算偏移量，确保下次拖动时位置正确
          // 注意：此时可能没有触摸点信息，所以我们只清理缩放相关的标志
          delete updatedElement.scaleMode;
          delete updatedElement.initialDistance;
          return updatedElement;
        }
        return el;
      });
      
      this.setData({
        addedElements: updatedElements
      });
      return;
    }
    
    // 清除偏移量数据（普通拖动结束时）
    const updatedElements = this.data.addedElements.map((element: any) => {
      if (element.id === id) {
        const newElement = { ...element };
        delete newElement.offsetX;
        delete newElement.offsetY;
        return newElement;
      }
      return element;
    });
    
    this.setData({
      addedElements: updatedElements
    });
  },

  // 触摸取消事件
  onTouchCancel(e: any) {
    this.onTouchEnd(e);
  },

  exportImage() {
  if (!this.data.selectedBackground && this.data.backgroundType !== 'color') {
    wx.showToast({ title: '请先选择背景', icon: 'none' });
    return;
  }
  wx.showLoading({ title: '正在生成…' });

  const query = wx.createSelectorQuery();
  query.select('#tempCanvas')
       .fields({ node: true, size: true })
       .exec(res => {
         const canvas = res[0].node;
         const ctx    = canvas.getContext('2d');
         const dpr    = wx.getSystemInfoSync().pixelRatio;
         const { bgImageWidth, bgImageHeight } = this.data;

         // 1. 设置画布物理像素
         canvas.width  = bgImageWidth;
         canvas.height = bgImageHeight;
         
         // 计算缩放比例
         const ratioX = bgImageWidth / this.data.canvasDisplayWidth;
         const ratioY = bgImageHeight / this.data.canvasDisplayHeight;

         // 2. 准备绘制任务
         const jobs = [];
         
         // 如果是纯色背景，先绘制纯色背景
         if (this.data.backgroundType === 'color') {
           jobs.push({
             type: 'color',
             color: this.data.selectedBackgroundColor,
             x: 0,
             y: 0,
             w: bgImageWidth,
             h: bgImageHeight
           });
         } 
         // 如果是图片背景，先绘制背景图片
         else if (this.data.selectedBackground) {
           jobs.push({
             type: 'image',
             src: this.data.selectedBackground,
             x: 0,
             y: 0,
             w: bgImageWidth,
             h: bgImageHeight
           });
         }

         // 添加元素绘制任务
         jobs.push(...this.data.addedElements.map((el: any) => ({
           type: 'image',
           src: el.src,
           x: el.x * ratioX,     // 根据比例调整x坐标
           y: el.y * ratioY,     // 根据比例调整y坐标
           w: el.width * ratioX, // 根据比例调整宽度
           h: el.height * ratioY // 根据比例调整高度
         })));

         // 3. 串行加载并绘制
         let i = 0;
         const next = () => {
           if (i >= jobs.length) {           // 全部画完
             wx.canvasToTempFilePath({
               canvas,                       // 2D 画布对象
               fileType: 'png',
               quality: 1,
               success: r => {
                 wx.hideLoading();
                 wx.saveImageToPhotosAlbum({
                   filePath: r.tempFilePath,
                   success: () => wx.showToast({ title: '已保存到相册' }),
                   fail: ()   => wx.showToast({ title: '保存失败', icon: 'none' })
                 });
               },
               fail: console.error
             });
             return;
           }
           const job = jobs[i++];
           
           // 绘制纯色背景
           if (job.type === 'color') {
             ctx.fillStyle = job.color;
             ctx.fillRect(job.x, job.y, job.w, job.h);
             next();
             return;
           }
           
           // 绘制图片
           const img = canvas.createImage();
           img.onload = () => {
             ctx.drawImage(img, job.x, job.y, job.w, job.h);
             next();          // 画完再画下一张
           };
           img.onerror = e => {
             console.error('图片加载失败', job.src, e);
             next();          // 出错也继续，避免卡死
           };
           img.src = job.src;
         };
         next();
       });
}
});